import os
import logging
import jieba
import re
import numpy as np
from collections import Counter

logger = logging.getLogger(__name__)

class SentimentAnalyzer:
    def __init__(self):
        self._load_dictionaries()
    
    def _load_dictionaries(self):
        """加载情感词典"""
        try:
            # 创建默认词典目录
            sentiment_dir = os.path.join('data', 'sentiment')
            os.makedirs(sentiment_dir, exist_ok=True)
            
            # 加载积极词典
            self.pos_words = self._load_dict(os.path.join(sentiment_dir, 'positive.txt'), self._get_default_positive_words())
            
            # 加载消极词典
            self.neg_words = self._load_dict(os.path.join(sentiment_dir, 'negative.txt'), self._get_default_negative_words())
            
            # 加载强调词
            self.intensifiers = self._load_dict(os.path.join(sentiment_dir, 'intensifiers.txt'), self._get_default_intensifiers())
            
            # 加载否定词
            self.negations = self._load_dict(os.path.join(sentiment_dir, 'negations.txt'), self._get_default_negations())
            
            # 创建词权重字典
            self.word_weights = {}
            for word in self.pos_words:
                self.word_weights[word] = 1.0
            for word in self.neg_words:
                self.word_weights[word] = -1.0
            
            logger.info(f"情感分析词典加载成功: 积极词 {len(self.pos_words)}个, 消极词 {len(self.neg_words)}个")
        except Exception as e:
            logger.error(f"加载情感词典失败: {str(e)}")
            # 创建默认空词典
            self.pos_words = self._get_default_positive_words()
            self.neg_words = self._get_default_negative_words()
            self.intensifiers = self._get_default_intensifiers()
            self.negations = self._get_default_negations()
            self.word_weights = {w: 1.0 for w in self.pos_words}
            self.word_weights.update({w: -1.0 for w in self.neg_words})
    
    def _load_dict(self, filepath, default_words):
        """从文件加载词典，如果文件不存在则创建并使用默认词典"""
        if os.path.exists(filepath):
            with open(filepath, 'r', encoding='utf-8') as f:
                words = set(line.strip() for line in f if line.strip())
            return words
        else:
            # 如果文件不存在，创建文件并写入默认词
            with open(filepath, 'w', encoding='utf-8') as f:
                for word in default_words:
                    f.write(f"{word}\n")
            return default_words
    
    def _get_default_positive_words(self):
        """获取默认积极情感词"""
        return set(['喜欢', '好', '棒', '赞', '优秀', '满意', '开心', '高兴', '快乐', '幸福', '欣赏', 
                  '支持', '爱', '推荐', '感谢', '点赞', '精彩', '美好', '友善', '热心', '细致', 
                  '周到', '耐心', '专业', '可靠', '有用', '值得', '精确', '正确', '贴心'])
    
    def _get_default_negative_words(self):
        """获取默认消极情感词"""
        return set(['讨厌', '差', '烂', '糟糕', '失望', '不满', '生气', '愤怒', '痛苦', '难过', 
                  '反对', '批评', '恨', '垃圾', '废物', '无聊', '敷衍', '粗心', '糊弄', '马虎', 
                  '过时', '过度', '混乱', '误导', '错误', '不准确', '骗人', '浪费', '无用', '不值'])
    
    def _get_default_intensifiers(self):
        """获取默认强调词"""
        return set(['非常', '很', '极其', '特别', '格外', '尤其', '最', '太', '相当', '十分',
                  '超级', '真的', '真是', '极度', '万分', '异常', '绝对', '甚至', '格外'])
    
    def _get_default_negations(self):
        """获取默认否定词"""
        return set(['不', '没', '不是', '没有', '别', '莫', '勿', '非', '无', '未', '否', '毫无', 
                  '决不', '绝不', '根本不', '完全不', '并非', '并未', '并不'])
    
    def analyze(self, text):
        """分析文本情感，返回情感得分和负面强度"""
        if not text:
            return {"sentiment_score": 0, "negative_intensity": 0}
        
        try:
            # 分词
            words = jieba.lcut(text)
            
            # 上下文分析（考虑否定词和强调词）
            sentiment_values = []
            i = 0
            while i < len(words):
                word = words[i]
                value = self.word_weights.get(word, 0)
                
                # 检查前面的否定词
                if i > 0 and words[i-1] in self.negations:
                    value = -value
                
                # 检查前面的强调词
                if i > 0 and words[i-1] in self.intensifiers:
                    value = value * 1.5
                
                sentiment_values.append(value)
                i += 1
            
            # 计算情感得分（-1到1之间）
            if not sentiment_values:
                sentiment_score = 0
            else:
                non_zero_values = [v for v in sentiment_values if v != 0]
                sentiment_score = np.mean(non_zero_values) if non_zero_values else 0
            
            # 计算负面情感强度（用于决定是否拒绝）
            negative_words = [w for w in words if w in self.neg_words]
            negative_intensity = len(negative_words) / len(words) if words else 0
            
            return {
                "sentiment_score": sentiment_score,
                "negative_intensity": negative_intensity
            }
        except Exception as e:
            logger.error(f"情感分析失败: {str(e)}")
            return {"sentiment_score": 0, "negative_intensity": 0}

# 创建单例实例
sentiment_analyzer = SentimentAnalyzer() 